package com.jdd.modules.rabbitMq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jdd.common.api.vo.Result;
import com.jdd.common.constant.CommonConstant;
import com.jdd.common.constant.MonthlyRabbitmqConstant;
import com.jdd.common.entity.RabbitMqMessage;
import com.jdd.common.util.MonthlyUploadHttpUtils;
import com.jdd.modules.parkcar.entity.ParkBlackList;
import com.jdd.modules.parkcar.entity.ParkSpace;
import com.jdd.modules.parkcar.service.IParkBlackListService;
import com.jdd.modules.parkcar.service.IParkSpaceService;
import com.jdd.modules.parkmonthly.dto.MonthlyCardDelayDto;
import com.jdd.modules.parkmonthly.entity.*;
import com.jdd.modules.parkmonthly.service.*;
import com.jdd.modules.parkmonthly.vo.AddMonthlySpace;
import com.jdd.modules.parkmonthly.vo.MonthlyCardEditInfoVO;
import com.jdd.modules.system.vo.ParkWhiteListVO;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @version 1.0
 * @Description:
 * @author： jdd尚岳
 * @Date: 2022-01-08 15:08
 */
@Component
@Slf4j
public class ParkCloudMonthlyListener {

    private  String parkAdminUrl;
    @Resource
    private ITaskMonthlyCardInfoService iMonthlyCardInfoService;
    @Resource
    private IMonthlyDepartmentService departmentService;
    @Resource
    private IPermissionGroupService   iPermissionGroupService;
    @Resource
    private IMonthlyPackageInfoService monthlyPackageInfoService;
    @Resource
    private MonthlyUploadHttpUtils monthlyUploadHttpUtils;
    @Resource
    private IPermissionAreaService permissionAreaService;
    @Resource
    private IParkBlackListService parkBlackListService;
    @Resource
    private IParkSpaceService spaceService;
    @RabbitListener(queues = "${park.monthly.queue}")
    @RabbitHandler
    public void receiveMessage(@Payload String body, @Headers Map<String, Object> headers, Channel channel) throws IOException {
        log.info("接收到云端消息{}", body);
        Long deliveryTag = (Long) headers.get(AmqpHeaders.DELIVERY_TAG);
        RabbitMqMessage rabbitMqMessage = null;
        try {
            rabbitMqMessage = JSON.parseObject(body, RabbitMqMessage.class);
        } catch (Exception e) {
            log.error("消息转换异常", e.getMessage());
            //非法消息，抛弃此条消息
            channel.basicNack(deliveryTag, false, false);
            return;
        }

        if (null == rabbitMqMessage || StringUtils.isBlank(rabbitMqMessage.getMessageType()) || StringUtils.isBlank(rabbitMqMessage.getMessageBody())) {
            log.info("空消息{}", JSON.toJSONString(rabbitMqMessage));
            //空消息，抛弃此条消息
            channel.basicNack(deliveryTag, false, false);
            return;
        }

        //处理消息
        try {
            process(rabbitMqMessage, deliveryTag, channel);
            //确认消息
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("处理消息异常：{}", e.getMessage());
            //抛弃此条消息
            channel.basicNack(deliveryTag, false, false);
        }

    }
    /**
     * @return void
     * @Description 业务不同异常处理(消息确认 、 消息返回队列 、 消息抛弃)
     * @Author wanglei
     * @Date 2021-06-02 17:28
     * @Param [rabbitMqMessage, deliveryTag, channel]
     * @version 1.0
     **/
    private void process(RabbitMqMessage rabbitMqMessage, Long deliveryTag, Channel channel) throws IOException {
        /**
         * 月卡新增
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_MONTH_CARD_ADD.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型月卡新增");

            MonthlyCardInfo monthlyCardInfo = JSONObject.parseObject(rabbitMqMessage.getMessageBody(), MonthlyCardInfo.class);
            iMonthlyCardInfoService.addMonthlyCardInfo(monthlyCardInfo);
            return;
        }
        /**
         * 月卡延期
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_MONTH_CARD_UPDATE.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型月卡延期");
            MonthlyCardEditInfoVO monthlyCardDelayDto = JSON.parseObject(rabbitMqMessage.getMessageBody(), MonthlyCardEditInfoVO.class);
              iMonthlyCardInfoService.issueUpdateMonthlyCardDelay(monthlyCardDelayDto);
            return;
        }
        /**
         * 月卡注销
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_MONTH_CARD_DELETE.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型月卡注销");

            MonthlyCardInfo monthlyCardInfo = JSON.parseObject(rabbitMqMessage.getMessageBody(), MonthlyCardInfo.class);

           iMonthlyCardInfoService.getMonthlyCardConcel(monthlyCardInfo);
            return;
        }
        /**
         * 月卡修改
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_MONTH_CARD_UPDATES.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型月卡修改");
            MonthlyCardInfo monthlyCardInfo = JSON.parseObject(rabbitMqMessage.getMessageBody(), MonthlyCardInfo.class);
               iMonthlyCardInfoService.editMonthlyCards(monthlyCardInfo);
         return;
        }
        /**
         * 月租套餐新增
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_MONTH_CARD_PACKAGE_ADD.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型月租套餐新增");
            MonthlyPackageInfo monthlyCardInfo = JSON.parseObject(rabbitMqMessage.getMessageBody(), MonthlyPackageInfo.class);
            monthlyPackageInfoService.save(monthlyCardInfo);
            String messageId = monthlyCardInfo.getMessageId();
            AddMonthlySpace addMonthlySpace = new AddMonthlySpace();
            addMonthlySpace.setJudge(false);
            addMonthlySpace.setStr(messageId);
              monthlyUploadHttpUtils.postMonthlyUpload("",addMonthlySpace);

            return;
        }
        /**
         * 月租套餐修改
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_MONTH_CARD_PACKAGE_UPDATE.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型月租套餐修改");
            MonthlyPackageInfo monthlyCardInfo = JSON.parseObject(rabbitMqMessage.getMessageBody(), MonthlyPackageInfo.class);
            monthlyPackageInfoService.updateById(monthlyCardInfo);
            String messageId = monthlyCardInfo.getMessageId();
            AddMonthlySpace addMonthlySpace = new AddMonthlySpace();
            addMonthlySpace.setJudge(false);
            addMonthlySpace.setStr(messageId);
            monthlyUploadHttpUtils.postMonthlyUpload("",addMonthlySpace);
        }
        /**
         * 月租套餐删除
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_MONTH_CARD_PACKAGE_DELETE.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型月租套餐删除");
            String id = rabbitMqMessage.getMessageBody();
            monthlyPackageInfoService.removeById(id);
            return;
        }
        /**
         * 更新月卡车部门组织表
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_MONTH_CARD_DEPART.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型更新月卡车部门组织表");
            MonthlyDepartment monthlyDepartment = JSON.parseObject(rabbitMqMessage.getMessageBody(), MonthlyDepartment.class);
            departmentService.requestCloudMonthlyDepartment(monthlyDepartment.getParkCode());
        }


        /**
         * 月卡车权限-区域
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_MONTH_CARD_PERMISSION.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型为月卡车权限-区域");
            String parkCode = rabbitMqMessage.getMessageBody();
            iPermissionGroupService.obtainAdminMonthlyPermission(parkCode);
            return;
        }


        /**
         * 车位新增
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_MONTH_CARD_SPACE_ADD.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型为车位新增");
            List<ParkSpace> parkSpaces = JSON.parseArray(rabbitMqMessage.getMessageBody(), ParkSpace.class);
                spaceService.addParkSpaces(parkSpaces);
                return;
        }
        /**
         * 车位删除
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_MONTH_CARD_SPACE_DELETE.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型为车位删除");
            String id = rabbitMqMessage.getMessageBody();
            spaceService.removeById(id);
            return;
        }
        /**
         * 消息类型为黑白名单新增
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_PARK_BLACK_WHITE_LIST_ADD.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型为黑白名单新增!");
            String id = rabbitMqMessage.getMessageBody();
            ParkWhiteListVO parkBlackList = JSON.parseObject(rabbitMqMessage.getMessageBody(), ParkWhiteListVO.class);
            parkBlackListService.issueAddParkBlackListMessage(parkBlackList);
            return;
        }
        /**
         * 消息类型为黑白名单修改
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_PARK_BLACK_WHITE_LIST_UPDATES.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型为黑白名单修改!");
            String id = rabbitMqMessage.getMessageBody();
            ParkWhiteListVO parkBlackList = JSON.parseObject(rabbitMqMessage.getMessageBody(), ParkWhiteListVO.class);
            parkBlackListService.issueUpdateParkBlackListMessage(parkBlackList);
            return;
        }
        /**
         * 消息类型为黑白名单删除
         */
        if (MonthlyRabbitmqConstant.MESSAGE_TYPE_NEW_PARK_BLACK_WHITE_LIST_DELETE.equals(rabbitMqMessage.getMessageType())){
            log.info("消息类型为黑白名单删除!");
             String id = rabbitMqMessage.getMessageBody();
            parkBlackListService.delectById(id);
            return;
        }
    }

}
